package com.hyjy.music.fragment

import android.content.Context
import android.graphics.drawable.AnimationDrawable
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.hyjy.music.MusicViewModel
import com.hyjy.music.R
import com.hyjy.music.base.BaseFragment
import com.hyjy.music.bean.MusicBean
import com.hyjy.music.databinding.FragmentMusiclistBinding
import com.hyjy.music.util.RecyclerViewCommonAdapter
import com.hyjy.music.util.convertToPinYin
import com.hyjy.music.util.format
import com.hyjy.music.util.showToast


/**
 * 音乐列表Fragment
 */
class MusicListFragment : BaseFragment<FragmentMusiclistBinding>() {
    companion object {
        fun newInstance(): MusicListFragment {
            val fragment = MusicListFragment()
            val args = Bundle()
            fragment.arguments = args
            return fragment
        }
    }

    private var musicAdapter: MusicAdapter? = null
    private lateinit var mainFragment: MainFragment
    private lateinit var musicViewModel: MusicViewModel
    private lateinit var linearLayoutManager: LinearLayoutManager

    override fun initViewBinding(inflater: LayoutInflater): FragmentMusiclistBinding {
        return FragmentMusiclistBinding.inflate(inflater)
    }

    override fun initData() {
        mainFragment = requireParentFragment() as MainFragment
        musicViewModel = mainFragment.musicViewModel
        context?.run {
            linearLayoutManager = LinearLayoutManager(this)
            musicAdapter = MusicAdapter(
                this,
                musicViewModel.getMusicList(),
                R.layout.music_list_item,
                object : RecyclerViewCommonAdapter.OnItemListener {
                    // 点击事件
                    override fun onItemClick(view: View, position: Int) {
                        mainFragment.myBinder?.run {
                            val musicBean = musicViewModel.getMusicList()[position]
                            if (musicBean == musicViewModel.currentMusicBean.value) {
                                if (!isMusicPlaying()) {
                                    // 相同位置并且没有播放,点击开始播放
                                    mainFragment.handlePlayOrPause(this)
                                }
                            } else {
                                // 不同位置，切换另一首歌曲
                                mainFragment.switchMusic(this, musicBean)
                            }
                        }
                    }
                })
            binding?.recyclerView?.layoutManager = linearLayoutManager
            binding?.recyclerView?.adapter = musicAdapter
            // 添加分割线
            val decoration = DividerItemDecoration(this, DividerItemDecoration.VERTICAL)
            binding?.recyclerView?.addItemDecoration(decoration)
        }

        // 字母搜索
        binding?.letterSearchBar?.setOnLetterCheckedListener {
            showToast(this)
            // 集合是排序过的,第一个匹配的就设置为当前
            for (i in 0 until musicViewModel.getMusicList().size) {
                val title: String = musicViewModel.getMusicList()[i].title
                val pinyin = title.convertToPinYin()
                if (TextUtils.equals(this, pinyin.substring(0, 1))) {
                    showToast("$this→$title")
                    if (linearLayoutManager.findLastCompletelyVisibleItemPosition() < i || linearLayoutManager.findFirstCompletelyVisibleItemPosition() > i) {
                        binding?.recyclerView?.scrollToPosition(i)
                    }
                    break
                }
            }
        }
    }

    fun updateUI() {
        musicAdapter?.refreshData(musicViewModel.getMusicList())
        // 设置ListView被选中的位置
        binding?.recyclerView?.run {
            post {
                val position = musicViewModel.getMusicPlayingPosition()
                if (position == -1) return@post
                if (linearLayoutManager.findLastCompletelyVisibleItemPosition() < position
                    || linearLayoutManager.findFirstCompletelyVisibleItemPosition() > position
                ) {
                    scrollToPosition(position)
                }
            }
        }
    }

    inner class MusicAdapter(
        context: Context,
        dataList: List<MusicBean>,
        @LayoutRes itemLayoutRes: Int,
        listener: OnItemListener? = null
    ) : RecyclerViewCommonAdapter<MusicBean>(context, dataList, itemLayoutRes, listener) {

        override fun getItemViewId(): IntArray {
            return intArrayOf(R.id.tv_title, R.id.tv_singer, R.id.tv_duration, R.id.iv_playing)
        }

        override fun setItemData(holder: ViewHolder, position: Int, item: MusicBean) {
            val duration = item.duration.toInt()
            holder.setTextView(R.id.tv_title, item.title)
                .setTextView(R.id.tv_singer, item.singer)
                .setTextView(R.id.tv_duration, duration.format())
            // 给正在播放的歌曲设置一个动画
            val imageView = holder.getItemChildView<ImageView>(R.id.iv_playing)
            if (item == musicViewModel.currentMusicBean.value) {
                imageView?.visibility = View.VISIBLE
                // 防止空指针异常,绑定服务了myBinder可能还未被赋值了
                mainFragment.myBinder?.run {
                    val animationDrawable = imageView?.background as? AnimationDrawable
                    if (isMusicPlaying()) {
                        animationDrawable?.start()
                    } else {
                        animationDrawable?.stop()
                    }
                }
            } else {
                imageView?.visibility = View.GONE
            }
        }
    }
}